<template>
  <el-dialog
    v-model="visible"
    title="用户详情"
    width="900px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="user-detail">
      <div v-if="userDetail" class="detail-content">
        <!-- 基本信息 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <h3>基本信息</h3>
          </template>
          
          <div class="basic-info">
            <div class="info-left">
              <el-avatar :src="getFullImageUrl(userDetail.user.avatar_url)" :size="80">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
            </div>
            
            <div class="info-right">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户ID">{{ userDetail.user.id }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ userDetail.user.nickname || '未设置' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userDetail.user.phone || '未绑定' }}</el-descriptions-item>
                <el-descriptions-item label="性别">
                  <el-tag v-if="userDetail.user.gender === 1" type="primary" size="small">男</el-tag>
                  <el-tag v-else-if="userDetail.user.gender === 2" type="danger" size="small">女</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="userDetail.user.is_active ? 'success' : 'danger'" size="small">
                    {{ userDetail.user.is_active ? '活跃' : '禁用' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">{{ userDetail.user.created_at }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-card>

        <!-- 统计信息 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <h3>统计信息</h3>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ userDetail.statistics.orders_count }}</div>
                <div class="stat-label">订单数量</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ userDetail.statistics.activities_count }}</div>
                <div class="stat-label">参与活动</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-number">{{ userDetail.relations.friends.length + userDetail.relations.blacklist.length }}</div>
                <div class="stat-label">关系总数</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 自定义属性 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-header">
              <h3>自定义属性</h3>
              <el-button type="primary" size="small" @click="handleEditAttributes">
                <el-icon><edit /></el-icon>
                编辑属性
              </el-button>
            </div>
          </template>
          
          <div v-if="Object.keys(userDetail.attributes).length > 0" class="attributes-list">
            <el-tag
              v-for="(value, key) in userDetail.attributes"
              :key="key"
              size="large"
              class="attribute-tag"
            >
              <strong>{{ key }}:</strong> {{ value }}
            </el-tag>
          </div>
          <el-empty v-else description="暂无自定义属性" :image-size="60" />
        </el-card>

        <!-- 用户关系 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="section-header">
              <h3>用户关系</h3>
              <el-button type="primary" size="small" @click="handleEditRelations">
                <el-icon><user /></el-icon>
                管理关系
              </el-button>
            </div>
          </template>
          
          <el-tabs>
            <el-tab-pane label="好友列表" :name="'friends'">
              <div v-if="userDetail.relations.friends.length > 0">
                <div 
                  v-for="relation in userDetail.relations.friends" 
                  :key="relation.id"
                  class="relation-item"
                >
                  <el-avatar :src="getFullImageUrl(relation.target.avatar_url)" :size="32">
                    <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                  </el-avatar>
                  <div class="relation-info">
                    <div class="relation-name">{{ relation.target.nickname }}</div>
                    <div class="relation-time">{{ relation.created_at }}</div>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无好友" :image-size="60" />
            </el-tab-pane>
            
            <el-tab-pane label="黑名单" :name="'blacklist'">
              <div v-if="userDetail.relations.blacklist.length > 0">
                <div 
                  v-for="relation in userDetail.relations.blacklist" 
                  :key="relation.id"
                  class="relation-item"
                >
                  <el-avatar :src="getFullImageUrl(relation.target.avatar_url)" :size="32">
                    <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                  </el-avatar>
                  <div class="relation-info">
                    <div class="relation-name">{{ relation.target.nickname }}</div>
                    <div class="relation-time">{{ relation.created_at }}</div>
                  </div>
                </div>
              </div>
              <el-empty v-else description="黑名单为空" :image-size="60" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑用户</el-button>
      </span>
    </template>

    <!-- 属性编辑对话框 -->
    <UserAttributesDialog
      v-model="attributesDialogVisible"
      :user="userDetail?.user"
      @updated="fetchUserDetail"
    />

    <!-- 关系管理对话框 -->
    <UserRelationsDialog
      v-model="relationsDialogVisible"
      :user="userDetail?.user"
      @updated="fetchUserDetail"
    />
  </el-dialog>
</template>

<script>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserDetail } from '@/api/user'
import UserAttributesDialog from './UserAttributesDialog.vue'
import UserRelationsDialog from './UserRelationsDialog.vue'

export default {
  name: 'UserDetailDialog',
  components: {
    UserAttributesDialog,
    UserRelationsDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    userId: {
      type: [Number, String],
      default: null
    }
  },
  emits: ['update:modelValue', 'updated'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const loading = ref(false)
    const userDetail = ref(null)
    const attributesDialogVisible = ref(false)
    const relationsDialogVisible = ref(false)
    const imageBaseUrl = ref(process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn')

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val && props.userId) {
        fetchUserDetail()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    // 获取用户详情
    const fetchUserDetail = async () => {
      if (!props.userId) return
      
      loading.value = true
      try {
        const response = await getUserDetail(props.userId)
        userDetail.value = response.data
      } catch (error) {
        ElMessage.error('获取用户详情失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      userDetail.value = null
    }

    // 编辑用户
    const handleEdit = () => {
      emit('edit', userDetail.value.user)
      handleClose()
    }

    // 编辑属性
    const handleEditAttributes = () => {
      attributesDialogVisible.value = true
    }

    // 编辑关系
    const handleEditRelations = () => {
      relationsDialogVisible.value = true
    }

    // 头像URL处理
    function getFullImageUrl(url) {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/avatar/')) return imageBaseUrl.value + url;
      return `${imageBaseUrl.value}/uploads/avatar/${url.replace(/^uploads[\/\\]avatar[\/\\]/, '')}`;
    }

    return {
      visible,
      loading,
      userDetail,
      attributesDialogVisible,
      relationsDialogVisible,
      fetchUserDetail,
      handleClose,
      handleEdit,
      handleEditAttributes,
      handleEditRelations,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.user-detail {
  max-height: 600px;
  overflow-y: auto;
}

.section-card {
  margin-bottom: 20px;
}

.section-card:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  color: #303133;
}

.basic-info {
  display: flex;
  gap: 20px;
}

.info-left {
  flex-shrink: 0;
}

.info-right {
  flex: 1;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.attributes-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.attribute-tag {
  padding: 8px 12px;
  border-radius: 6px;
}

.relation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.relation-item:last-child {
  border-bottom: none;
}

.relation-info {
  flex: 1;
}

.relation-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.relation-time {
  font-size: 12px;
  color: #909399;
}

:deep(.el-descriptions__label) {
  width: 100px;
}
</style> 